package com.caogen.cg_wl_kt.net

import com.caogen.cg_wl_kt.config.Config
import com.caogen.cg_wl_kt.utils.YDLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * 项目名称: cg_wl_kt
 * Packages:com.caogen.cg_wl_kt.net
 * author: FSW
 * 创建日期: 2024/2/26 11:37
 * Describe:
 *
 */
object HttpApi {

    // 协程作用域
    val io = CoroutineScope(Dispatchers.IO)
    val main = CoroutineScope(Dispatchers.Main)

    // 线程作用域
    fun io(): CoroutineScope {
        return CoroutineScope(Dispatchers.IO)
    }

    // 线程作用域
    fun main(): CoroutineScope {
        return CoroutineScope(Dispatchers.Main)
    }

    // OA base_url
    private val URL = UrlProtocol.HOST
    val api: HttpApiService = Retrofit.Builder().baseUrl(URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(Config.getClient())
        .build().create(HttpApiService::class.java)

    // 扩展Retrofit
    suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    var request = call.request()
                    YDLog.logd("************start*********************************")
                    YDLog.logd(request.toString())
                    YDLog.logd(response.toString())
                    YDLog.logd(body.toString())
                    YDLog.logd("************end***********************************")
                    if (null != body) {
                        continuation.resume(body)
                    } else {
                        continuation.resumeWithException(Exception("xxxx:response.body is null"))
                    }
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    var request = call.request()
                    YDLog.loge("************start*********************************")
                    YDLog.loge(request.toString())
                    YDLog.loge(t.toString())
                    YDLog.loge("************end***********************************")
                    continuation.resumeWithException(t)
                }
            })
        }
    }

}